<?php
namespace Api\Controller;

use Api\Controller\BaseController;

class UserController extends BaseController
{
    function getPrivateDoctor()
    {
        $did = D('DoctorUser')->getFieldByUserId($_POST['uid'], 'doctor_id');

        if ($re['msg'] = D('DoctorUser')->getError()) {
            $re['status'] = 0;
        } else {
            if ($did) {
                $re['status'] = 1;
                $re['data']['doctor_id'] = $did;
            } else {
                $re['status'] = 0;
                $re['msg'] = '没有私人医生';
                $re['info'] = '没有私人医生';
            }
        }
        $map['uid'] = is_login();
        $map['status']=array('egt',0);
        $model = D('ApplyPrivateDoctor');
        if ($re['status']==0 && $model->where($map)->count()) {
            $re['status'] = 0;
            $re['status2'] = 2;
            $re['msg'] = '您已经提交过绑定私人医生的申请，请等待系统为您匹配合适的医生';
            $re['info'] = '您已经提交过绑定私人医生的申请，请等待系统为您匹配合适的医生';
        }
        $this->ajaxReturn($re);
    }

    function applyConsultation()
    {
        $_POST['uid'] = is_login();
        $_POST['username'] = $_SESSION['user_auth']['username'];
        $_POST['type'] = 21;
        $model = D('ApplyConsultation');
        //以下语句只管最新的申请是否结束.0为结束1为申请中
        $data=$model->where(array('doctor_id'=>I('post.doctor_id'),'uid'=>I('post.uid')))->order('add_time desc')->find();
        if ((empty($data) || $data['status']==0) && $model->create()) {
            if ($model->add()) {
                $re['status'] = 1;
                $re['data'] = '申请发送成功，等系统工作人员联系你！';
            } else {
                $re['status'] = 0;
                $re['msg'] = $model->getError();
                $re['info'] = $model->getError();
            }
        } elseif(empty($data)) {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
            $re['info'] = $model->getError();
        }elseif($data['status']==1){
            $re['status'] = 0;
            $re['msg'] = '您已经有正在进行的会诊申请了,请耐心等待医生确认';
            $re['info'] = '您已经有正在进行的会诊申请了,请耐心等待医生确认';
        }
        $this->ajaxReturn($re);
    }

    function question()
    {
        $_POST['uid'] = is_login();
        $_POST['inituid'] = is_login();
        $_POST['pid'] = I('post.pid', 0,'intval');
        $_POST['topid'] = I('post.topid', 0,'intval');
        $_POST['username'] = get_username($_POST['uid']);
        $model = D('question');
        if ($model->create()) {
            if ($id = $model->add()) {
                if ($_POST['topid'] === 0) {
                    $data['id'] = $id;
                    $data['topid'] = $id;
                }
                $model->save($data);
                $re['status'] = 1;
                $re['data'] = '提问发送成功!';
            } else {
                $re['status'] = 0;
                $re['msg'] = $model->getError();
                $re['info'] = $model->getError();
            }
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
            $re['info'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function continueAsk()
    {
        $uid = is_login();
        $id = I('post.id');
        unset($_POST['id']);
        $_POST['inituid'] = $uid;
        $_POST['uid'] = $uid;
        $_POST['username'] = get_nickname($_POST['uid']);
        $_POST['pid'] = $id;
        $_POST['topid'] = $id;
        $model = D('question');
        if ($model->create()) {
            if ($rs = $model->add()) {
                $map['inituid'] = is_login();
                $map['id'] = $id;
                $data['status'] = -1;
                if ($model->where($map)->save($data) !== false) {
                    $re['status'] = 1;
                    $re['data'] = $rs;
                } else {
                    $re['status'] = 0;
                    $re['msg'] = $model->getError();
                    $model->delete($rs);
                }
            } else {
                $re['status'] = 0;
                $re['addon'] = 2;
                $re['msg'] = $model->getError();
            }
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function gameover()
    {
        $map['id'] = I('post.id');
        $map['inituid'] = is_login();
        $data['status'] = 1;
        $model = M('question');
        if ($rs = $model->where($map)->save($data)) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function questionNoReply()
    {
        $model = D('question');
        $map['uid'] = is_login();
        $map['status'] = array('elt', 0);
        $map['pid'] = 0;
        $rs = $model->where($map)->order('status asc, id desc')->select();
        if ($rs  || $rs === null) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {

            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function questionHasReply()
    {

        $model = D('question');
        $map['uid'] = is_login();
        $map['pid'] = 0;
        $map['status'] = array('gt', 1);
        $rs = $model->where($map)->order('status asc, id desc')->select();
        if ($rs  || $rs === null) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['sql'] = $model->getLastSql();
            F('qqqq', $model->getLastSql());
            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function questionEnd()
    {
        $model = D('question');
        $map['uid'] = is_login();
        $map['pid'] = 0;
        $map['status'] = 1;
        if ($rs = $model->where($map)->order('id desc')->select()) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    //获取与问题相关的回答以及再提问。。。。
    function getOneQuestion()
    {
        $model = D('question');
        $map['topid'] = I('post.id');
        $map['inituid'] = is_login();
        if ($rs = $model->where($map)->select()) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }


    //consultationList
    function consultationList()
    {
        $model = D('ApplyConsultation');
        $map['uid'] = is_login();
        //以下语句只管最新的申请是否结束.0为结束1为申请中
        $map['status'] = 1;
        if ($rs = $model->where($map)->select()) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }


    //获取已建立未付款订单
    function consultationOrderList()
    {
        $map['uid'] = is_login();
        $map['status'] = 0;
        $model = D('ConsultationOrder');
        if ($rs = $model->where($map)->select()) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['data'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function getConsultationOrder()
    {
        $map['id'] = I('post.id');
        $map['uid'] = is_login();
        $model = D('ConsultationOrder');
        $rs = $model->where($map)->find();
        if ($rs || $rs === null) {
            $re['status'] = 1;
            $re['data'] = $rs;
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    /**
     * 客户端修改头像
     * @param pic string  base64Encode
     * @param token string  username  in ucenter_member 数据表中
     */
    public function uploadAvatar()
    {
        $pic = I('post.pic', '');
        $aUid = is_login();
        $aExt = "jpg";
        if (empty($pic) || stripos($pic, 'base64') < 1) {
            $this->error('没有图片信息');
        }
        $dir = './Uploads/Avatar/' . $aUid;
        if (is_dir($dir)) {
            $dh = opendir($dir);
            while ($file = readdir($dh)) {
                if ($file != "." && $file != "..") {
                    $fullpath = $dir . "/" . $file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        } else
            mkdir($dir, 0777, true);

        preg_match('/^(data:\s*image\/(\w+);base64,)/', $pic, $result);
        $aExt = $result[2];
        if ($aExt == 'jpeg')
            $aExt = 'jpg';

        $filename = "/Uploads/Avatar/" . $aUid . "/original." . $aExt;
        $filepath = "." . $filename;

        if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $pic)))) {
            $res = M('Avatar')->where(array('uid' => $aUid))->find();
            if (empty($res)) {
                M('avatar')->add(array('uid' => $aUid, 'status' => 1, 'is_temp' => 0, 'path' => "/" . $aUid . "/original." . $aExt, 'create_time' => time()));
            } else {
                M('avatar')->where(array('uid' => $aUid))->save(array('status' => 1, 'is_temp' => 0, 'path' => "/" . $aUid . "/original." . $aExt, 'create_time' => time()));
            }
            clean_query_user_cache($aUid, array('avatar256', 'avatar128', 'avatar64', 'avatar32', 'avatar512'));
            $avatar = query_user(array('avatar256', 'avatar128', 'avatar64', 'avatar32', 'avatar512'));
            $this->success('更新成功', 'refresh', array('avatar' => $avatar));
        }
    }

    /**
     * 客户端获取用户信息
     * @param token string username in ucenter_member数据表
     * @param ajax string   强制使用ajax提交的话请使用此项 设置为1即可  设置为0表示禁止使用ajax (此项目仅限于直接访问)
     */
    public function getUserInfo()
    {
        $info = UCenterMember()->field('id,username,email,mobile,type')->find(is_login());

        if (empty($info)) {
            $this->error('操作失败');
        } else {
            $user = query_user(array('nickname', 'signature','birthday', 'email', 'mobile', 'avatar128', 'rank_link', 'sex', 'pos_province', 'pos_city', 'pos_district', 'pos_community'), $aUid);
            $info['user'] = $user;
            $this->success('操作成功', 'refresh', array('data' => $info));
        }
    }

    /**
     * 客户端获取用户扩展资料
     * @param token string  username in ucenter_member数据表
     */
    public function getUserExtendInfo()
    {
        $profile_group_list = A('Ucenter/Config')->_profile_group_list($uid);
        if (!empty($profile_group_list)) {
            $info_list = A('Ucenter/Config')->_info_list($profile_group_list[0]['id'], $uid);
            foreach ($profile_group_list as &$v) {
                $v['fields'] = A('Ucenter/Config')->_getExpandInfo($v['id']);
            }

            $data['info_list'] = $info_list;
            $data['profile_group_id'] = $profile_group_list[0]['id'];
            $this->success('操作成功', 'refresh', $data);
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 购买套装
     */
    public function buyDevices()
    {
        $remark = I('post.remark', '', 'op_t');
        $mobile = I('post.mobile', '', 'op_t');
        if ($mobile && $remark) {
            $data['remark'] = $remark;
            $data['mobile'] = $mobile;
            $data['uid'] = get_uid();
            $result = M('DeviceBuy')->add($data);
            if ($result) {
                $this->success('操作成功,id为' . $result, 'refresh');
            } else
                $this->error(M('DeviceBuy')->getError());
        } else {
            $this->error('参数不完整');
        }
    }

    /**
     * 写诊断记录
     */
    public function writerLog()
    {
        $uid = is_login();
        $did = I('post.doctor_id', 0, 'intval');
        if (empty($did)) {
            $this->error('医生id获取失败!');
        }
        $content = I('post.content', '', 'op_t');
        if (empty($content)) {
            $this->error('记录内容不能为空');
        }
        $order_id = I('post.order_id', 0, 'op_t');
        $happen_time = I('post.happen_time', date('Y-m-d H:i:s'), 'op_t');
        $modle = M('UserLog');
        $data['user_id'] = $uid;
        if ($order_id)
            $data['order_id'] = $order_id;
        $data['happen_time'] = $happen_time;
        $data['content'] = $content;
        $data['doctor_id'] = $did;
        $result = $modle->add($data);
//        var_dump($modle->getLastSql());
        if ($result)
            $this->success('添加成功,id为' . $result, 'refresh');
        else
            $this->error('操作失败,' . $modle->getError());
    }

    /**
     * 查看诊断记录
     */
    public function getLog()
    {
        $uid = is_login();
        $id = I('post.id', 0, 'intval');
        $did = I('post.doctor_id', 0, 'intval');
        if (empty($did) && empty($id))
            $this->error('医生id获取错误或者没有指定记录id!');
        if ($id)
            $where['id'] = $id;
        if ($did)
            $where['doctor_id'] = $did;
        $model = M('UserLog');

        $perPage = I('post.perPage', 5, 'intval');
        $page = I('post.page', 1, 'intval');
        $maxPage = $count / $perPage;

        if ($page != 1 && $page > $maxPage)
            $this->error('没有此页面');
        $where['user_id'] = $uid;
        $count = $model->where($where)->count();
        $list = $model->where($where)->page($page, $perPage)->select();
//        var_dump($model->getLastSql());
        if (empty($list))
            $this->error('没有数据!');
        else
            $this->success('获取成功', 'refresh', array('count' => $count, 'list' => $list));
    }


    public function bindFamily()
    {
        $_POST['family_id'] = is_login();
        $model = D('Family');
        if ($model->create()) {
            if ($model->add()) {
                $re['status'] = 1;
                $re['data'] = '添加成功！';
            } else {
                $re['status'] = 0;
                $re['msg'] = $model->getError();
            }
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    function familyList()
    {
        $map['family_id'] = is_login();
        $model = D('Family');
        if ($data = $model->where($map)->select()) {
            $re['status'] = 1;
            $re['data'] = $data;
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }

    /*
     * 申请私人医生
     */
    function applyPrivateDoctor()
    {
        $_POST['uid'] = is_login();
        $map['uid'] = is_login();
//        $_POST['add_time'] = time();
//        $_POST['status'] = 1;
        $model = D('ApplyPrivateDoctor');
        if ($model->where($map)->select()) {
            $re['status'] = 0;
            $re['msg'] = '您已经提交过申请';
        } else {
            $lat = I('post.lat');
            $lng = I('post.lng');
            $location = $lat . "," . $lng; //lat 纬度 lng经度
            $url = "http://api.map.baidu.com/geocoder/v2/?ak=" . C('BAIDUKEY') . "&location=" . $location . "&output=json";
            $json = file_get_contents($url);
            $result = json_decode($json, true);
            if ($result['status'] == 0) {//0表示正常
                $result = $result['result'];
                $address = $result['addressComponent'];
                $city = $address['city'];
                $province = $address['province'];
                $district = $address['district'];
                //现查找省
                $districtModel = M('District');
                $provinceid = $districtModel->where(array('name' => $province, 'level' => 1))->getField('id');
                if (!empty($provinceid) && $city)
                    $cityid = $districtModel->where(array('name' => $city, 'level' => 2, 'upid' => $provinceid))->getField('id');
                if (!empty($cityid) && $district)
                    $districtid = $districtModel->where(array('name' => $district, 'level' => 3, 'upid' =>$cityid))->getField('id');
                $memberModel = M('Member');
                $memberInfo['uid'] = is_login();
                if ($provinceid)
                    $memberInfo['pos_province'] = $provinceid;
                if ($cityid)
                    $memberInfo['pos_city'] = $cityid;
                if ($districtid)
                    $memberInfo['pos_district'] = $districtid;
                if (count($memberInfo)>1)
                    $memberModel->save($memberInfo);
            }
        }
        if ($model->create()) {
            if ($model->add()) {
                $re['status'] = 1;
                $re['data'] = '添加成功！';
            } else {
                $re['status'] = 0;
                $re['msg'] = $model->getError();
            }
        } else {
            $re['status'] = 0;
            $re['msg'] = $model->getError();
        }
        $this->ajaxReturn($re);
    }


    /**
     * 获取地区列表
     * @param upid string id yjr_district表
     * @return json
     */
    public function getDistrict(){
        $upid=I('post.upid',0,'intval');
//        if($upid)
            $where['upid']=$upid;
        $data=M('District')->where($where)->select();
        if(!empty($data))
            $this->success('操作成功',null,array('data'=>$data));
        else
            $this->error('非法请求!');
    }
}